<template>
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录 -->
    <div class="loginBox">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <section class="nav">
        <a
          href="#"
          :class="{ active: isShowContent }"
          @click="isShowContent = true"
          >手机号码登录</a
        >
        |
        <a href="#" :class="{ active: !isShowContent }" @click="showQrCode"
          >微信扫码登录</a
        >
      </section>
      <div class="content">
        <!-- 手机号码登录 -->
        <div class="phoneLogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入手机号"
              v-model.trim="phoneNum"
              ref="phone"
            />
          </div>
          <div class="row hk">
            <!-- <input type="text" class="ipt" placeholder="向右滑动" /> -->
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              class="ipt"
              placeholder="请输入短信验证码"
              v-model="code"
            />
            <button
              class="btn btnCode"
              :class="{ hasCount: isShowCount }"
              @click="getCode"
              v-show="!isShowCount"
            >
              获取验证码
            </button>
            <button
              class="btn btnCode"
              :class="{ hasCount: isShowCount }"
              v-show="isShowCount"
            >
              {{ count }} s
            </button>
          </div>
          <div class="row">
            <button class="btnLogin btn" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 微信二维码登录 -->
        <div id="weixin" class="qrcode" v-show="!isShowContent"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import { validatePhoneNumber } from "@/utils";
import { SendSMSAPI, PhoneReginAPI, BindPhoneAPI } from "@/request/api.js";
export default {
  data() {
    return {
      isShowContent: true,
      msg: "向右滑动",
      hkstate: -1,
      phoneNum: "",
      count: 59,
      isShowCount: false,
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      changeIsLogined: "loginStates/changeIsLogined",
      changeIsShowToast: "showToast/changeIsShowToast",
    }),
    ...mapActions({
      asyncIsShowToast: "showToast/asyncIsShowToast",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "耗时 " + ms + "s";
      this.hkstate = 1;
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
      this.hkstate = -1;
    },
    //登录按钮方法
    async submitFn() {
      //验证
      if (!this.toVerify()) return;
      if (this.code.trim == "") {
        alert("请输入验证码");
        return;
      }

      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await BindPhoneAPI({
          phone: this.phoneNum.trim(),
          verifyCode: this.code,
          uuid,
        });
      } else {
        //发登录请求
        res = await PhoneLoginAPI({
          verifyCode: this.code,
          phone: this.phoneNum.trim(),
        });
      }
      if (!res) {
        return;
      }
      // alert("登录成功");
      this.asyncIsShowToast({
        show: true,
        msg: "登录成功",
        type: "success",
      });
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      this.changeIsShowLoginModal(false);
      this.changeIsLogined(true);

      localStorage.removeItem("uuid");
      this.$router.push(this.$route.path);
      // location.reload();
    },
    //手机号验证和滑块验证
    toVerify() {
      if (!validatePhoneNumber(this.phoneNum)) {
        // alert("请输入正确的手机号");
        this.asyncIsShowToast({
          show: true,
          msg: "请输入正确的手机号",
          type: "warning",
        });

        this.$refs.phone.focus();
        return false;
      }
      // 拼图验证
      if (this.hkstate == -1) {
        // alert("请滑动拼图验证码");
        this.asyncIsShowToast({
          show: true,
          msg: "请滑动拼图验证码",
          type: "warning",
        });
        return false;
      }
      return true;
    },
    //获取验证码，并启动倒计时
    async getCode() {
      // let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!this.toVerify()) return;

      if (this.isShowCount) return;

      let res = await SendSMSAPI({
        phone: this.phoneNum,
      });
      console.log("发送验证码", res);

      if (!res) return;
      if (res.code == 0) {
        this.countdown();
      }
    },
    //倒计时
    countdown() {
      clearInterval(timer);
      this.isShowCount = true;
      let timer = null;
      timer = setInterval(() => {
        this.count--;
        if (this.count == 0) {
          clearInterval(timer);
          this.isShowCount = false;
          this.count = 59;
        }
      }, 1000);
    },
    showQrCode() {
      this.isShowContent = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href:
          "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLC5pbXBvd2VyQm94IC5pbmZvew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9ICAgIA0KLmltcG93ZXJCb3ggcXJjb2Rlew0KICAgIG1hcmdpbi10b3A6IDIwcHg7DQp9",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  .mask {
    background: rgba(0, 0, 0, 0.4);
    width: 100%;
    height: 100%;
  }
  .loginBox {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 555px;
    height: 423px;
    margin: auto;
    background: url("../assets/img/login-box-bg.png");
    .close {
      position: absolute;
      right: 60px;
      top: 16px;
      height: 22px;
      width: 22px;
      background: url("../assets/img/close.png");
      cursor: pointer;
    }
    .nav {
      display: flex;
      justify-content: center;
      font-size: 20px;
      padding-top: 50px;
      a {
        padding: 0 10px;
        color: #999;
        text-decoration: none;
        &.active {
          color: #333;
        }
      }
    }
    .content {
      margin-top: 30px;
      .phoneLogin {
        .row {
          width: 360px;
          margin: 0 auto 20px;
          height: 50px;
          display: flex;
          justify-content: space-between;
        }
        .hk {
          display: block;
        }
        .ipt {
          box-shadow: 0;
          flex: 1;
          height: 48px;
          // width: ;
          outline: none;
          text-indent: 1em;
        }
        .btn {
          color: #fff;
          background-color: #0a328e;
          border: none;
          cursor: pointer;
        }
        .hasCount {
          background: #777;
        }
        .btnCode {
          margin-left: 10px;
          line-height: 50px;
          width: 100px;
          text-align: center;
          // background: #0a328e;
          color: white;
        }
        .btnLogin {
          width: 100%;
          height: 50px;
          line-height: 50px;
        }
      }
    }
    #weixin {
      /* background-color: #fcf; */
      display: flex;
      justify-content: center;
      margin-top: -20px;
    }
  }
}
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>